package com.libmessagecenter

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import com.huawei.hms.push.HmsMessageService
import com.huawei.hms.push.HmsMessaging
import com.huawei.hms.push.RemoteMessage
import com.libbase.utils.JsonUtils
import com.libbase.utils.genericType
import com.libmessagecenter.models.Message

class HmsPushMessageService : HmsMessageService() {
    companion object {
        const val TAG = "HmsPushMessageService"

        val pushSDK = object : PushSDKInterface {
            override  fun register(context: Context, appId: String?, appKey: String?) {
                HmsMessaging.getInstance(context).isAutoInitEnabled = true
            }
        }
    }

    override fun onNewToken(token: String, bundle: Bundle) {
        Log.i(TAG, "onNewToken $token")
        if (token.isNotEmpty()) {
            LibMessageCenter.instance.register(token)
        }
    }

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        val messages: Map<String, String> = JsonUtils.json.fromJson(
            remoteMessage.data,
            genericType<Map<String, String>>()
        )

        messages["appMessage"]?.let {
            val message = JsonUtils.json.fromJson(it, Message::class.java)
            LibMessageCenter.instance.onMessageWillPresent(message)
        }
    }
}